// 轻量 i18n 工具（CommonJS），可在 TS/JS 中通过 require 使用
const zhCN = require('./zh-CN');
const enUS = require('./en-US');
const zhHK = require('./zh-HK');

const DICTS = {
  'zh-CN': zhCN || {},
  'en-US': enUS || {},
  'zh-HK': zhHK || {}
};

let currentLang = 'zh-CN';
const listeners = [];

try {
  const saved = wx.getStorageSync('app:lang');
  if (saved && DICTS[saved]) currentLang = saved;
} catch (e) {}

function getLang() {
  return currentLang;
}

function setLang(lang) {
  if (!DICTS[lang]) return;
  currentLang = lang;
  try {
    wx.setStorageSync('app:lang', lang);
  } catch (e) {}
  // 通知监听者
  listeners.forEach((cb) => {
    try { cb && cb(currentLang); } catch (_) {}
  });
}

function getDict() {
  return DICTS[currentLang] || DICTS['zh-CN'];
}

function t(key, params) {
  const dict = getDict();
  const value = key.split('.').reduce((acc, k) => (acc && acc[k] != null ? acc[k] : undefined), dict);
  let str = value != null ? String(value) : key;
  if (params && typeof params === 'object') {
    str = str.replace(/\{(\w+)\}/g, (_, p1) => (params[p1] != null ? String(params[p1]) : ''));
  }
  return str;
}

function onLangChange(callback) {
  if (typeof callback === 'function') listeners.push(callback);
  return () => {
    const idx = listeners.indexOf(callback);
    if (idx >= 0) listeners.splice(idx, 1);
  };
}

module.exports = {
  getLang,
  setLang,
  t,
  getDict,
  onLangChange
}; 